import { TabBar } from 'antd-mobile'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { useStreams } from '@/lib/utils'
import { ReactComponent as MessageFilledIcon } from '@/mobile/assets/message-filled.svg'
import { ReactComponent as MessageIcon } from '@/mobile/assets/message.svg'
import { ReactComponent as MineFilledIcon } from '@/mobile/assets/mine-filled.svg'
import { ReactComponent as MineIcon } from '@/mobile/assets/mine.svg'
import services from '@/services'
import { ContactType } from '@/services/contacts'

const tabs: Record<string, string> = { '/contacts': 'contacts', '/mine': 'mine' }

export function Layout() {
  const appLocation = useLocation()
  const tab = tabs[appLocation.pathname]
  return tab === undefined ? <Outlet /> : <Content tab={tab} />
}

function Content({ tab }: { tab: string }) {
  const appNavigate = useNavigate()
  const changeTab = useCallback(
    (tab: string) => {
      const pathname = Object.entries(tabs).find(entry => entry[1] === tab)?.[0]
      if (pathname !== undefined) appNavigate(pathname, { replace: true })
    },
    [appNavigate],
  )

  const [metaUnreads, mutes] = useStreams(services.chat.metas.unreads, services.groups.mutes)
  const unread = useMemo(
    () =>
      metaUnreads.reduce((sum, item) => {
        if (item.type === ContactType.group && mutes.has(item.contactId)) return sum
        return sum + item.unread
      }, 0),
    [metaUnreads, mutes],
  )

  return <div css={s.layout}>
    <Outlet />
    <footer css={s.footer}>
      <TabBar safeArea activeKey={tab} onChange={changeTab}>
        <TabBar.Item
          key="contacts"
          icon={active => (active ? <MessageFilledIcon /> : <MessageIcon />)}
          title="聊天"
          badge={unread > 99 ? '...' : unread || ''}
        />
        <TabBar.Item
          key="mine"
          icon={active => (active ? <MineFilledIcon /> : <MineIcon />)}
          title="我的"
        />
      </TabBar>
    </footer>
  </div>
}

const s = {
  layout: css`
    display: flex;
    flex-direction: column;
    height: 100vh;
  `,
  footer: css`
    border-top: 1px solid rgba(0, 0, 0, 0.08);
    padding: 11px 0 6px;
    .adm-tab-bar-item-title-with-icon {
      margin-top: 4px;
    }
    .adm-tab-bar-item-title {
      color: #676767;
    }
    .adm-tab-bar-item-active .adm-tab-bar-item-title {
      color: #000;
      font-weight: bold;
    }
  `,
}
